/**
 * @Author: likang xie
 * @Date: 2019-11-13 14:15:57
 * @Usage: 选择图片/文件
 */

import upload from "@/utils/upload";
import { appUpload } from "@/utils/upload";
import toast from "@/utils/toast";
import config from "@/config";

/**
 * @method chooseImage 选择图片
 * @param residue 最大选择数量
 */
export let chooseImage = (residue = 1) => {
  return new Promise((resolve, reject) => {
    uni
      .chooseImage({
        count: residue,
      })
      .then((chunk) => {
        let [err, res] = chunk;
        if (res) {
          console.log("res1111",res)
          let paths = res.tempFilePaths;
          uni.setStorageSync("pathName", res.tempFiles[0].name);
          uni.setStorageSync("pathSize", res.tempFiles[0].size);
          console.log("选中的文件信息：", paths);

          uni.showLoading({
            title: "正在上传..",
            mask: true,
          });

          // 上传图片队列
          let tasks = paths.map((item) => {
            // alert(1)
            return upload(item);
          });
          

          // 全部图片上传成功
          Promise.all(tasks)
            .then((res) => {
              resolve(res);
              uni.hideLoading();
            })
            .catch((err) => {
              console.error(err);
              toast("上传失败，请重试");
            });
        }
      });
  });
};

/**
 * @method chooseFile 选择文件
 * @param residue 最大选择数量
 */
export let chooseFile = (residue = 1) => {
  return new Promise((resolve, reject) => {
    // #ifdef MP-WEIXIN
    wx.chooseMessageFile({
      count: residue,
      type: "file",
      success: (res) => {
        console.log("0000",res)
        let paths = res.tempFiles.map((item) => item.path);
        console.log("选中的文件信息：", paths);

        uni.showLoading({
          title: "正在上传..",
          mask: true,
        });

        // 上传图片队列
        let tasks = paths.map((item) => {
          return upload(item);
        });

        // 全部文件上传成功
        Promise.all(tasks)
          .then((res) => {
            resolve(res);
            uni.hideLoading();
          })
          .catch((err) => {
            console.error(err);
            toast("上传失败，请重试");
          });
      },
    });
    // #endif

    // #ifdef APP-PLUS
    if (uni.getSystemInfoSync().platform === "android") {
      let main = plus.android.runtimeMainActivity();
      let Intent = plus.android.importClass("android.content.Intent");
      let intent = new Intent(Intent.ACTION_GET_CONTENT);

      // 设置任意类型
      intent.setType("*/*");
      intent.addCategory(Intent.CATEGORY_OPENABLE);
      main.startActivityForResult(intent, 1);

      main.onActivityResult = function(requestCode, resultCode, data) {
        if (1 == requestCode) {
          plus.android.importClass(data);
          // 获得文件路径
          let fileData = data.getData();
          let path = plus.android.invoke(fileData, "getPath");

          // 转换成文件储存真实路径
          // path = plus.io.convertLocalFileSystemURL(path);
          path = plus.io.convertAbsoluteFileSystem(path);
          path = path.replace("/raw/", "");
          if (!path.includes("storage/emulated/0")) {
            path = "/storage/emulated/0" + path;
            path = path.replace("/external_files", "");
          }

          console.log("path:" + path);
          uni.showLoading({
            title: "正在上传..",
            mask: true,
          });

          appUpload(path)
            .then((res) => {
              resolve([res]);
              uni.hideLoading();
            })
            .catch((e) => {
              uni.hideLoading();
              toast("上传失败，请重试");
            });
        }
      };
    } else {
      // ios 上传
      plus.gallery.pick(
        (path) => {
          uni.showLoading({
            title: "正在上传..",
            mask: true,
          });
          upload(path)
            .then((res) => {
              resolve([res]);
              console.log(res);
              uni.hideLoading();
            })
            .catch((e) => {
              uni.hideLoading();
              toast("上传失败，请重试");
            });
        },
        (err) => {
          console.log(e, "取消选择图片");
        },
        { filter: "image" }
      );
    }
    // #endif
  });
};

export let urlTobase64 = (url) => {
  uni.request({
    url: url,
    method: "GET",
    responseType: "arraybuffer",
    success: (res) => {
      let base64 = wx.arrayBufferToBase64(res.data); //把arraybuffer转成base64
      base64 = "data:image/jpeg;base64," + base64; //不加上这串字符，在页面无法显示
      // console.log(base64);
      return base64;
    },
  });
};
